package com.sinosoft.system.util.generate;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Date;

public class GenDaoMysql {
	private String packageOutDaoPath = "com.sinosoft.system.primary.dao";//指定实体生成所在包的路径  
	private String packageOutDaoImpPath = "com.sinosoft.system.primary.dao.imp";//指定实体生成所在包的路径  
    private String projectPath = "D:/QNH/git/morningglory/src/main/java/"; //项目路径
    private String authorName = "shangxp";//作者名字  
    private String tablename = "sys_credentials";//表名
    private String[] tcnames; // 表列名数组
    private String[] colnames; // 列名数组  
    private String[] colTypes; //列名类型数组  
    private int[] colSizes; //列名大小数组  
    private boolean f_util = false; // 是否需要导入包java.util.*  
    private boolean f_sql = false; // 是否需要导入包java.sql.*  
      
    //数据库连接  
    private static final String URL ="jdbc:mysql://192.168.1.10:3306/appdb";  
    private static final String NAME = "root";  
    private static final String PASS = "root";  
    private static final String DRIVER ="com.mysql.jdbc.Driver";  
  
    /* 
     * 构造函数 
     */  
    public GenDaoMysql(){  
        //创建连接  
        Connection con = null;  
        //查要生成实体类的表  
        String sql = "select * from " + tablename;  
        PreparedStatement pStemt = null;  
        try {  
            try {  
                Class.forName(DRIVER);  
            } catch (ClassNotFoundException e1) {  
                // TODO Auto-generated catch block  
                e1.printStackTrace();  
            }  
            con = DriverManager.getConnection(URL,NAME,PASS);  
            pStemt = con.prepareStatement(sql);  
            ResultSetMetaData rsmd = pStemt.getMetaData();  
            int size = rsmd.getColumnCount()-1;   //统计列  
            tcnames = new String[size]; 
            colnames = new String[size];  
            colTypes = new String[size];  
            colSizes = new int[size];  
            for (int i = 0; i < size; i++) {
            	if(!"is_del".equalsIgnoreCase(rsmd.getColumnName(i + 1))){
            		
            	tcnames[i] = rsmd.getColumnName(i + 1);
                colnames[i] = initStr(rsmd.getColumnName(i + 1));  
                colTypes[i] = rsmd.getColumnTypeName(i + 1);  
                  
                if(colTypes[i].equalsIgnoreCase("datetime")){  
                    f_util = true;  
                }  
                if(colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")){  
                    f_sql = true;  
                }  
                colSizes[i] = rsmd.getColumnDisplaySize(i + 1);  
            }}  
              
            String daoContent = parseDao();  
            String outputPath = projectPath+this.packageOutDaoPath.replace(".", "/")+"/"+initCLassName(tablename) + "Dao.java"; 
            outWrite(outputPath,daoContent);
            
            String daoImpContent = parseDaoImp(tcnames,colnames,colTypes,colSizes); 
            String outputImpPath = projectPath+this.packageOutDaoImpPath.replace(".", "/")+"/"+initCLassName(tablename) + "DaoJdbc.java"; 
            outWrite(outputImpPath,daoImpContent);
              
        } catch (SQLException e) {  
            e.printStackTrace();  
        } finally{  
          try {  
              con.close();  
          } catch (SQLException e) {  
                
              e.printStackTrace();  
          }  
        }  
    }
    /**
     * 
     */
    public void outWrite(String outputPath,String content){
    	try {  
            System.out.println(outputPath);
            FileWriter fw = new FileWriter(outputPath);  
            PrintWriter pw = new PrintWriter(fw);  
            pw.println(content);  
            pw.flush();  
            pw.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }
    }
  
    /** 
     * 功能：生成接口类主体代码 
     * @param colnames 
     * @param colTypes 
     * @param colSizes 
     * @return 
     */  
    private String parseDao() {  
        StringBuffer sb = new StringBuffer();  
        String entityName = initCLassName(tablename);
        String istName = initStr(tablename);
        //判断是否导入工具包  
        if(f_util){  
            sb.append("import java.util.Date;\r\n");  
        }  
        if(f_sql){  
            sb.append("import java.sql.*;\r\n");  
        }  
        sb.append("package " + this.packageOutDaoPath + ";\r\n");  
        sb.append("\r\n");
        sb.append("import java.util.List;\n\n");
        sb.append("import "+packageOutDaoPath.substring(0, packageOutDaoPath.lastIndexOf("."))+".entity."+entityName+";\n");
        //注释部分  
        sb.append("   /**\r\n");  
        sb.append("    * "+tablename+" Dao接口类\r\n");  
        sb.append("    * "+new Date()+" "+this.authorName+"\r\n");  
        sb.append("    */ \r\n");  
        //实体部分

        sb.append("\r\n\r\npublic interface " + entityName + "Dao {\r\n\t");  
        sb.append("public int insert"+entityName+"("+entityName+" "+istName+");\n\t");
        sb.append("public int update"+entityName+"("+entityName+" "+istName+");\n\t");
        sb.append("public int delete"+entityName+"(int id);\n\t");
        sb.append("public "+entityName+" select"+entityName+"(int id);\n\t");
        sb.append("public "+entityName+" select"+entityName+"(String[] queryKeys,Object[] queryValues);\n\t");
        sb.append("public int selectCount"+entityName+"();\n\t");
        sb.append("public int selectCount"+entityName+"(String[] queryKeys,Object[] queryValues);\n\t");
        sb.append("public List<"+entityName+"> selectLimit"+entityName+"(int start,int end);\n\t");
        sb.append("public List<"+entityName+"> selectLimit"+entityName+"(String[] queryKeys,Object[] queryValues);\n\t");
        sb.append("public List<"+entityName+"> selectAll"+entityName+"();\n\t");
        sb.append("public List<"+entityName+"> selectAll"+entityName+"(String[] queryKeys,Object[] queryValues);\n\t");
        sb.append("}\r\n");            
        //System.out.println(sb.toString());  
        return sb.toString();  
    }  
    /** 
     * 功能：生成实现类主体代码 
     * @param colnames 
     * @param colTypes 
     * @param colSizes 
     * @return 
     */  
    private String parseDaoImp(String[] tcnames,String[] colnames, String[] colTypes, int[] colSizes) {  
        StringBuffer sb = new StringBuffer();  
          
        //判断是否导入工具包  
        if(f_util){  
            sb.append("import java.util.Date;\r\n");  
        }  
        if(f_sql){  
            sb.append("import java.sql.*;\r\n");  
        }  
        sb.append("package " + this.packageOutDaoImpPath + ";\r\n");  
        sb.append("\r\n");  
        
        //实体部分
        String entityName = initCLassName(tablename);
        String istName = initStr(tablename);
        sb.append("import java.sql.ResultSet;\n");
        sb.append("import java.sql.SQLException;\n");
        sb.append("import java.util.List;\n\n");
        sb.append("import org.apache.log4j.Logger;\n");
        sb.append("import org.springframework.beans.factory.annotation.Autowired;\n");
        sb.append("import org.springframework.jdbc.core.JdbcTemplate;\n");
        sb.append("import org.springframework.jdbc.core.RowMapper;\n");
        sb.append("import org.springframework.stereotype.Repository;\n\n");
        sb.append("import "+packageOutDaoPath+"."+entityName+"Dao;\n");
        sb.append("import "+packageOutDaoPath.substring(0, packageOutDaoPath.lastIndexOf("."))+".entity."+entityName+";\n");
        sb.append("\r\n\r\n");
      //注释部分  
        sb.append("   /**\r\n");  
        sb.append("    * "+tablename+" DaoJdbc实现类\r\n");  
        sb.append("    * "+new Date()+" "+this.authorName+"\r\n");  
        sb.append("    */ \r\n");  
        
        sb.append("@Repository\n");
        sb.append("public class " + entityName + "DaoJdbc implements "+entityName+"Dao {\r\n");
        sb.append("	private static Logger log = Logger.getLogger(SysUserDaoJdbc.class);\n");
        sb.append("	@Autowired\n");
        sb.append("	private JdbcTemplate jdbcTemplate;\n\n");

        sb.append("	public JdbcTemplate getJdbcTemplate() {\n");
        sb.append("		return jdbcTemplate;\n");
        sb.append("	}\n\n");

        sb.append("	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {\n");
        sb.append("		this.jdbcTemplate = jdbcTemplate;\n");
        sb.append("	}\n\n");

        String insertStr = "	@Override\n";
        insertStr +="	public int insert"+entityName+"("+entityName+" "+istName+") {\n";
        insertStr += "		String sqlStr = \"insert into "+tablename+" (";
        for(int i=0;i<tcnames.length;i++){
        	insertStr +=" "+tcnames[i].toLowerCase()+",";
        }
        //insertStr=insertStr.substring(0, insertStr.lastIndexOf(","));
        insertStr += " is_del) values( ";
        for(int i=0;i<tcnames.length;i++){
        	insertStr +=" ?,";
        }
        //insertStr=insertStr.substring(0, insertStr.lastIndexOf(","));
        insertStr+=" 0 )\";\n";
        insertStr+="\t\tlog.debug(sqlStr+\"\\n\"+"+istName+".toString());\n";
        insertStr+="\t\ttry{\n\t\t\tObject[] args = {\n\t\t\t\t";
        for(int i=0;i<tcnames.length;i++){
        	insertStr += istName+".get"+initcap(colnames[i])+"(),\n\t\t\t\t";
        }
        insertStr=insertStr.substring(0, insertStr.lastIndexOf(","));
        insertStr+="\n\t\t\t};\n";
        insertStr+="\t\t\treturn jdbcTemplate.update(sqlStr, args);\n"
        		+ "\t\t}catch(Exception e){\n"
        		+"\t\t\tlog.error(\"数据添加异常 SQL：\"+sqlStr+\"\\n\"+"+istName+".toString()+e.getMessage());\n\t\t}"
        		+ "\n\t\treturn 0;\n"
        		+ "\t}\n\n";
        
        sb.append(insertStr);
     
        String uStr = "";
        uStr+= "	@Override\n";
        uStr+="	public int update"+entityName+"("+entityName+" "+istName+") {\n";
        uStr+="		String sqlStr = \"update "+tablename+" set ";
        for(int i=0;i<tcnames.length;i++){
        	uStr+=tcnames[i].toLowerCase()+" = ? , ";
        }
        uStr=uStr.substring(0, uStr.lastIndexOf(","));
        uStr+=" where id = ?\";\n";
        uStr+="\t\tlog.debug(sqlStr+\"\\n\"+"+istName+".toString());\n";
        uStr+="\t\ttry{\n";
        uStr+="\t\t\tObject[] args = {\n\t\t\t\t\t";
        for(int i=0;i<tcnames.length;i++){
        	uStr += istName+".get"+initcap(colnames[i])+"(),\n\t\t\t\t\t";
        }
        uStr+=istName+".getId()\n";
        uStr+="\t\t\t};\n";
        uStr+="\t\t\treturn jdbcTemplate.update(sqlStr, args);";
        uStr+= "\n\t\t}catch(Exception e){\n"
        		+"\t\t\tlog.error(\"数据更新异常 SQL：\"+sqlStr+\"\\n\"+"+istName+".toString()+e.getMessage());\n\t\t}"
        		+ "\n\t\treturn 0;\n";
        uStr+="\t}\n\n";
        
        sb.append(uStr);
        
        sb.append("	@Override\n");
        sb.append("	public int delete"+entityName+"(int id) {\n");
        sb.append("		String sqlStr = \"update "+tablename+" set is_del = 1  where id = ?\";\n");
        sb.append("		try{\n\t");
        sb.append("		Object[] args = {\n\t");
        sb.append("				id\n\t");
        sb.append("		};\n\t");
        sb.append("		return jdbcTemplate.update(sqlStr, args);\n\t");
        sb.append("	}catch(Exception e){\n\t");
        sb.append("		log.error(\"数据删除异常\"+sqlStr+\"\\nID=\"+id+\"\\n\"+e.getMessage());\n\t\t}");
        sb.append("	return 0;\n");
        sb.append("	}\n\n");
        
        sb.append("	@Override\n");
        sb.append("	public "+entityName+" select"+entityName+"(int id) {\n");
        sb.append("		String sqlStr = \"select * from "+tablename+" where is_del =0 and id = ?\";\n");
        sb.append("		log.debug(sqlStr+\"\\nID=\"+id);\n\t\ttry{\n");
        sb.append("		\tObject[] args = {\n");
        sb.append("				id\n");
        sb.append("		\t};\n");
        sb.append("		\treturn jdbcTemplate.queryForObject(sqlStr, args, new "+entityName+"Mapper());\n");
        sb.append("		}catch(Exception e){\n\t");
        sb.append("		log.error(\"数据删除异常\"+sqlStr+\"\\nID=\"+id+\"\\n\"+e.getMessage());\n\t\t}");
        sb.append("	return null;\n");
        sb.append("	}\n\n");
        
        sb.append("	@Override\n");
        sb.append("	public "+entityName+" select"+entityName+"(String[] queryKeys,Object[] queryValues) {\n");
        sb.append("		StringBuffer sqlStr = new StringBuffer(\"select * from "+tablename+" where is_del =0 \" );\n");
        sb.append("		if(queryKeys!=null && queryKeys.length!=0){\n");
        sb.append("			for(int i=0;i<queryKeys.length;i++){\n");
        sb.append("				sqlStr.append(\" and \"+queryKeys[i]+\"=? \");\n");
        sb.append("			}\n");
        sb.append("		}\n");
        sb.append("		log.debug(sqlStr.toString());\n\t\ttry{\n");
        sb.append("		\treturn jdbcTemplate.queryForObject(sqlStr.toString(), queryValues, new "+entityName+"Mapper());\n");
        sb.append("		}catch(Exception e){\n\t");
        sb.append("		log.error(\"数据查询异常\"+sqlStr.toString()+\"\\n\"+e.getMessage());\n\t\t}\n");
        sb.append("	\treturn null;\n");
        sb.append("	}\n\n");
        
        sb.append("	@Override\n");
        sb.append("	public int selectCount"+entityName+"() {\n");
        sb.append("		String sqlStr = \"select count(1) from "+tablename+" where is_del =0 \";\n");
        sb.append("		log.debug(sqlStr);\n\t\ttry{\n");
        sb.append("		\treturn jdbcTemplate.queryForObject(sqlStr, Integer.class);\n");
        sb.append("		}catch(Exception e){\n\t");
        sb.append("		log.error(\"数据查询异常\"+sqlStr+\"\\n\"+e.getMessage());\n\t\t}\n");
        sb.append("	\treturn 0;\n");
        sb.append("	}\n\n");

        sb.append("	@Override\n");
        sb.append("	public List<"+entityName+"> selectLimit"+entityName+"(int start, int end) {\n");
        sb.append("		String sqlStr = \"select * from "+tablename+" where is_del =0  limit ?,?\";\n");
        sb.append("		log.debug(sqlStr);\n\t\ttry{\n");
        sb.append("		Object[] args = {\n");
        sb.append("				start,\n");
        sb.append("				end\n");
        sb.append("		};\n");
        sb.append("		\treturn jdbcTemplate.query(sqlStr, args, new "+entityName+"Mapper());\n");
        sb.append("		}catch(Exception e){\n\t");
        sb.append("		log.error(\"数据查询异常\"+sqlStr+\"\\n\"+e.getMessage());\n\t\t}\n");
        sb.append("	\treturn null;\n");
        sb.append("	}\n\n");

        sb.append("	@Override\n");
        sb.append("	public List<"+entityName+"> selectAll"+entityName+"() {\n");
        sb.append("		String sqlStr = \"select * from "+tablename+" where is_del =0 \";\n");
        sb.append("		log.debug(sqlStr);\n\t\ttry{\n");
        sb.append("		\treturn jdbcTemplate.query(sqlStr, new "+entityName+"Mapper());\n");
        sb.append("		}catch(Exception e){\n\t");
        sb.append("		log.error(\"数据查询异常\"+sqlStr+\"\\n\"+e.getMessage());\n\t\t}\n");
        sb.append("	\treturn null;\n");
        sb.append("	}\n\n");

        sb.append("	@Override\n");
        sb.append("	public int selectCount"+entityName+"(String[] queryKeys,Object[] queryValues) {\n");
        sb.append("		StringBuffer sqlSb = new StringBuffer(\"select count(1) from "+tablename+" where is_del = 0 \");\n");
        sb.append("		if(queryKeys!=null && queryKeys.length!=0){\n");
        sb.append("			for(int i=0;i<queryKeys.length;i++){\n");
        sb.append("				sqlSb.append(\" and \"+queryKeys[i]+\"=? \");\n");
        sb.append("			}\n");
        sb.append("		}		\n");
        sb.append("		log.debug(sqlSb.toString());\n\t\ttry{\n");
        sb.append("		\treturn jdbcTemplate.queryForObject(sqlSb.toString(), queryValues,Integer.class);\n");
        sb.append("		}catch(Exception e){\n\t");
        sb.append("		log.error(\"数据查询异常\"+sqlSb.toString()+\"\\n\"+e.getMessage());\n\t\t}\n");
        sb.append("	\treturn 0;\n");
        sb.append("	}\n\n");

        sb.append("	@Override\n");
        sb.append("	public List<"+entityName+"> selectLimit"+entityName+"(String[] queryKeys,Object[] queryValues) {\n");
        sb.append("		StringBuffer sqlStr = new StringBuffer(\"select * from "+tablename+" where is_del =0 \" );\n");
        sb.append("		if(queryKeys!=null && queryKeys.length!=0){\n");
        sb.append("			for(int i=0;i<queryKeys.length-2;i++){\n");
        sb.append("				sqlStr.append(\" and \"+queryKeys[i]+\"=? \");\n");
        sb.append("			}\n");
        sb.append("		}\n");
        sb.append("		sqlStr.append(\" limit ?,?\");\n");
        sb.append("		log.debug(sqlStr.toString());\n\t\ttry{\n");
        sb.append("		\treturn jdbcTemplate.query(sqlStr.toString(), queryValues, new "+entityName+"Mapper());\n");
        sb.append("		}catch(Exception e){\n\t");
        sb.append("		log.error(\"数据查询异常\"+sqlStr.toString()+\"\\n\"+e.getMessage());\n\t\t}\n");
        sb.append("	\treturn null;\n");
        sb.append("	}\n\n");
        
        sb.append("	@Override\n");
        sb.append("	public List<"+entityName+"> selectAll"+entityName+"(String[] queryKeys,Object[] queryValues) {\n");
        sb.append("		StringBuffer sqlStr = new StringBuffer(\"select * from "+tablename+" where is_del =0 \" );\n");
        sb.append("		if(queryKeys!=null && queryKeys.length!=0){\n");
        sb.append("			for(int i=0;i<queryKeys.length;i++){\n");
        sb.append("				sqlStr.append(\" and \"+queryKeys[i]+\"=? \");\n");
        sb.append("			}\n");
        sb.append("		}\n");
        sb.append("		log.debug(sqlStr.toString());\n\t\ttry{\n");
        sb.append("		\treturn jdbcTemplate.query(sqlStr.toString(), queryValues, new "+entityName+"Mapper());\n");
        sb.append("		}catch(Exception e){\n\t");
        sb.append("		log.error(\"数据查询异常\"+sqlStr.toString()+\"\\n\"+e.getMessage());\n\t\t}\n");
        sb.append("	\treturn null;\n");
        sb.append("	}\n\n");
                
        String mStr = "";
        mStr+="	protected class "+entityName+"Mapper implements RowMapper<"+entityName+"> {\n";
        mStr+="		@Override\n";
        mStr+="		public "+entityName+" mapRow(ResultSet arg0, int arg1) throws SQLException {\n";
        mStr+="			"+entityName+" "+istName+" = new "+entityName+"();\n";
        mStr+="			if(arg0!=null){\n\t\t\t\t";
        for(int i=0;i<tcnames.length;i++){
        	mStr+=istName+".set"+initcap(colnames[i])+"(arg0.get"+initcap(sqlType2JavaType(colTypes[i]))+"(\""+tcnames[i].toLowerCase()+"\"));\n\t\t\t\t";
        }
        mStr+="}\n";
        mStr+="			return "+istName+";\n\t\t}  \n\t}\n}\n";
        sb.append(mStr);
        //System.out.println(sb.toString());  
        return sb.toString();  
    }    

      
    /** 
     * 功能：将输入字符串的首字母改成大写 
     * @param str 
     * @return 
     */  
    private String initcap(String str) {  
          
        char[] ch = str.toCharArray();  
        if(ch[0] >= 'a' && ch[0] <= 'z'){  
            ch[0] = (char)(ch[0] - 32);  
        }  
          
        return new String(ch);  
    }
    /** 
     * 功能：将输入字符串的'_'去掉，并把后续的首字母改成大写 ；初始化属性名
     * @param str 
     * @return 
     */
    private String initStr(String str){
    	str=str.toLowerCase();
    	StringBuffer sb = new StringBuffer();
    	if(str.contains("_")){
    		String[] strs = str.split("_");
    		sb.append(strs[0]);
    		for(int i=1; i<strs.length;i++){
    			sb.append(initcap(strs[i]));
    		}
    	}else{
    		sb.append(str);
    	}
    	return sb.toString();
    }
    /** 
     * 功能：将输入字符串的'_'去掉，并把后续的首字母改成大写 ,初始化属性名
     * @param str 
     * @return 
     */
    private String initCLassName(String str){
    	return initcap(initStr(str));
    }
  
    /** 
     * 功能：获得列的数据类型 
     * @param sqlType 
     * @return 
     */  
    private String sqlType2JavaType(String sqlType) {  
          
        if(sqlType.equalsIgnoreCase("bit")){  
            return "boolean";  
        }else if(sqlType.equalsIgnoreCase("tinyint")){  
            return "byte";  
        }else if(sqlType.equalsIgnoreCase("smallint")){  
            return "short";  
        }else if(sqlType.equalsIgnoreCase("int")){  
            return "int";  
        }else if(sqlType.equalsIgnoreCase("bigint")){  
            return "long";  
        }else if(sqlType.equalsIgnoreCase("float")){  
            return "float";  
        }else if(sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")   
                || sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")   
                || sqlType.equalsIgnoreCase("smallmoney")){  
            return "double";  
        }else if(sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")   
                || sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")   
                || sqlType.equalsIgnoreCase("text")){  
            return "String";  
        }else if(sqlType.equalsIgnoreCase("datetime")){  
            return "Date";  
        }else if(sqlType.equalsIgnoreCase("image")){  
            return "Blod";  
        }  
          
        return null;  
    }  
      
    /** 
     * 出口 
     * s
     * @param args 
     */  
    public static void main(String[] args) {  
          
        new GenDaoMysql();  
          
    }  
  
} 
